import lodash from 'lodash';

const serializer = <T>(value?: T): string => {
  if (!value) {
    return '';
  }
  return JSON.stringify(value);
};

const deserializer = <T>(value?: string): T | undefined => {
  if (!value) {
    return undefined;
  }
  return JSON.parse(value);
};

export function getItem<T>(key: string): T | undefined {
  const localCurrentUserStr = globalThis.localStorage.getItem(key);
  if (!localCurrentUserStr) {
    return undefined;
  }
  return deserializer<T>(localCurrentUserStr);
}

export function setItem<T>(key: string, value: T): void {
  globalThis.localStorage.setItem(key, serializer<T>(value));
}

export function removeItem(key: string): void {
  globalThis.localStorage.removeItem(key);
}

export function getKeysByPattern(pattern: any) {
  const result = [];
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    if (pattern.test(key)) {
      result.push(key);
    }
  }
  return result;
}

export function removeItems(keyPattern: any): void {
  // window.sfw.storage.removeItems(/^cscf_cache_DynamicComponentByCodeOneQuery\d+/)
  const matchingKeys = getKeysByPattern(keyPattern);
  lodash.forEach(matchingKeys, (key: any) =>
    globalThis.localStorage.removeItem(key),
  );
}

export const storage = {
  serializer,
  deserializer,
  getItem,
  setItem,
  removeItem,
  removeItems,
};
